package com.eunion.boot.security;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.eunion.core.LogUtil;
import com.eunion.web.admin.entity.AdminUser;
import com.eunion.web.admin.service.AdminAuthService;
import com.eunion.web.admin.service.AdminRoleService;
import com.eunion.web.admin.service.AdminUserService;

/**
 * 服务层，用于登录获取权限验证.
 * 
 * @since 2017年1月1日
 */
@Service("myUserDetailsService")
public class SysUserDetailsService implements UserDetailsService {

	@Autowired
	private AdminRoleService adminRoleService;

	@Autowired
	private AdminAuthService adminAuthService; 

	@Autowired
	private AdminUserService adminUserService;

	@Override
	public UserDetails loadUserByUsername(String userName)
	    throws UsernameNotFoundException {
		AdminUser user;
		try {
			user = adminUserService.findOneByUsername(userName);
		} catch (Exception e) {
			throw new UsernameNotFoundException("用户不存在");
		}
		if (user == null) {
			throw new UsernameNotFoundException("用户不存在");
		} else {
			List<String> auths = new ArrayList<String>();
			if (StringUtils.isNotBlank(userName) && userName.equals("admin")) {
				List<String> authList = adminAuthService.findAuths();
				auths.addAll(authList);
			} else {
				List<String> roles = adminRoleService.fingAllRolesByUsername(userName);
				if (roles != null && roles.size() > 0) {
					List<String> authList = adminAuthService.findAuthsByRoleCodes(roles);
					if (null != authList) {
						auths.addAll(authList);
					}
				}
			}
			LogUtil.get(this.getClass()).debug("admin has all ok permission:{}", auths);
			return new SysUserDetails(user, auths);

		}
	}
}
